package com.iemes.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.iemes.controller.index.BaseController;
import com.iemes.entity.CopyMoldFormMap;
import com.iemes.entity.EntryFormMap;
import com.iemes.entity.OrderFormMap;
import com.iemes.entity.OrderperFormMap;
import com.iemes.entity.ProcessFormMap;
import com.iemes.mapper.ProcessMapper;
import com.iemes.mapper.entry.EntryMapper;
import com.iemes.mapper.machine.ShapeMachineMapper;
import com.iemes.mapper.mould.CopyMoldMapper;
import com.iemes.mapper.order.OrderMapper;
import com.iemes.mapper.order.OrderpreMapper;
import com.iemes.mapper.planner.ClientPlannerMapper;
import com.iemes.service.OrderService;
import com.iemes.util.DateUtils;
import com.iemes.util.PublicUtils;

@Service
public class OrderServiceImpl extends BaseController implements OrderService {
	@Inject
	private OrderMapper orderMapper;
	@Inject
	private ClientPlannerMapper clientPlannerMapper;
	@Inject
	private ProcessMapper processMapper;
	@Inject
	private EntryMapper entryMapper;
	@Inject
	private ShapeMachineMapper shapeMachineMapper; // 成型机台
	@Inject
	private OrderpreMapper orderpreMapper; // 预排mapper
	@Inject
	private CopyMoldMapper copyMoldMapper; // 复制模
	
	@Override
	public List<Map<String, Object>> worktuough(OrderFormMap orderFormMap) {
		// **先获取叫料计划中需要交货的数据*/
		List<Map<String, Object>> clientPlannerFormMaps = clientPlannerMapper
				.getThroughPlanner(PublicUtils.Walkthrough_days);
		// **获取订单中需要预排的所有数据*/
		List<Map<String, Object>> orderFormMaps = orderMapper
				.getThroughOrder(PublicUtils.Walkthrough_days);
		
		for (int i = 0; i < orderFormMaps.size();i++) {
			if(Integer.valueOf(orderFormMaps.get(i).get("parent_id").toString())==0){
				orderFormMaps.remove(i);
				i--;
			}
		}
		for (Map<String, Object> order : orderFormMaps) {
			// for (Map<String, Object> planner : clientPlannerFormMaps) {
			for (int i = 0; i < clientPlannerFormMaps.size(); i++) {
				/** 第一层判断预排的订单中是否有另外的计划订单 */
				// 如果有再次判断订单中的计划时间是否比计划中的大
				// 如何没有则通过计划订单中的订单ID添加
				if (order.get("id") == clientPlannerFormMaps.get(i).get(
						"order_id")) {
						order.put("shipping_time", clientPlannerFormMaps.get(i)
								.get("shipping"));
						order.put("number",
								clientPlannerFormMaps.get(i).get("number"));
						clientPlannerFormMaps.remove(i);
						i--;
				}
			}
		}
		// 除去计划数据中与订单预排一样的数据后
		// 剩下的都是 最后交货日期在7天后 ，却在7天内需要泰源方交一部分货的
		for (Map<String, Object> map : clientPlannerFormMaps) {
			// 循环获取order_id
			OrderFormMap oMap = orderMapper.findbyFrist("id",
					map.get("order_id").toString(), OrderFormMap.class);
			oMap.put("shipping_time", map.get("shipping"));
			oMap.put("number", map.get("number"));
			orderFormMaps.add(oMap);
		}
		// 获取厂目前正在使用的原料
		EntryFormMap entryFormMap = entryMapper.getTodaypur();
		String brand = entryFormMap.getStr("name");
		// 获取成型工艺
		for (Map<String, Object> map : orderFormMaps) {
			ProcessFormMap processFormMap = getFormMap(ProcessFormMap.class);
			processFormMap.put("brand", brand);
			processFormMap.put("state", 1);
			processFormMap.put("mold_encode", map.get("mold_encode"));
			ProcessFormMap processFormMaps = processMapper
					.getProcessBycondition(processFormMap);
			// 将工艺绑定到订单中
			if (processFormMaps == null) {
				// 如果数据库中没有成型的工艺参数，
				// 需从试模参数中调取,并提醒这个模具需要量产成型的工艺参数
				processFormMap.put("state", 2);
				processFormMaps = processMapper
						.getProcessBycondition(processFormMap);
			}
			map.put("process", processFormMaps);
			// 计算此订单完成的时间周期
			Double ordernum = Double.valueOf(map.get("number").toString()); // 订单数量
			// 订单对应模具12小时的标准产能
			Double Standard_Capacity = Double.valueOf(processFormMaps.get(
					"Standard_Capacity").toString());
			// 获取时间需要做多久的时间
			double hour = ordernum * 12 / Standard_Capacity;
			int mintue = (int) (hour * 60);
			map.put("mintue", mintue);
			// 将上机日期定好
			Date ship_time = DateUtils.stringToDate(map.get("shipping_time")
					.toString());
			Calendar c = Calendar.getInstance();
			c.setTime(ship_time);
			c.add(Calendar.MINUTE, -(PublicUtils.Warehouse_reserve + mintue));
			map.put("up_moldTime", DateUtils.getDateTime(c.getTime()));
		}
		return orderFormMaps;
	}
	
	/**
	 * 保存预排
	 * 
	 * @throws Exception
	 */
	@Override
	public void getOrderpre(List<Map<String, Object>> orderList)
			throws Exception {
		
		// 获取现在正在做的预排表中的数据
		List<Map<String, Object>> orderperFormMaps = orderpreMapper
				.getRunningMachineNo();
		// 删除预排表中状态为等待的数据 state=2的所有数据

		orderpreMapper.deleteByAttribute("state", "2", OrderperFormMap.class);
		// 获取所有 好的成型机器编号
		List<Map<String, Object>> shapeMachineFormMaps = shapeMachineMapper
				.getMachinesTicking();
		if (orderperFormMaps.size() > 0 && shapeMachineFormMaps.size() > 0) {
			for (Map<String, Object> per : orderperFormMaps) {
				for (Map<String, Object> shape : shapeMachineFormMaps) {
					Integer smachine_no = Integer.valueOf(shape.get(
							"machine_no").toString());
					Integer pmachine_no = Integer.valueOf(per.get("machine_no")
							.toString());
					if (smachine_no == pmachine_no) {
						// 把此时间正在做的机台号 赋予可完成时间
						shape.put("Machine_time", per.get("finish_time"));
						break;
					}
				}
			}
		}
		// 把所有的预排数据按机器型号区分
		for (Map<String, Object> map : orderList) {
			ProcessFormMap processFormMap = getFormMap(ProcessFormMap.class);
			processFormMap = (ProcessFormMap) map.get("process");
			for (Map<String, Object> shape : shapeMachineFormMaps) {
				Integer type1 = processFormMap.getInt("Machine_model");
				Integer type2 = Integer.valueOf(shape.get("machine_type")
						.toString());
				if (type1 == type2) {
					// 获取所有预排中 每个机台的最后时间
					List<Map<String, Object>> orderpreFormMaps = orderpreMapper
							.getLastper();
					OrderperFormMap orderperFormMap = getFormMap(OrderperFormMap.class);
					// 判断是否这个机台
					// .1判断此订单在预排表中是否存在
					List<Map<String, Object>> oreList = orderpreMapper
							.getOrderNoExist(map.get("id").toString());
					if (oreList.size() > 0) {
						break;
					}
					// 判断此机型在预排中出现的最大次数
					List<Map<String, Object>> shapeMaps = orderpreMapper
							.getAllMachineCount(shape.get("machine_type")
									.toString());
					boolean flag = true;
					List<Map<String, Object>> shapeallMap = shapeMachineMapper
							.getMachinesTicking();
					
					if (shapeallMap.size() > 0 && shapeMaps.size() > 0) {
						for (int i = 0; i < shapeallMap.size(); i++) {
							for (int j = 0; j < shapeMaps.size(); j++) {
								// 排除已存在的机台
								Integer machine_no1 = Integer
										.valueOf(shapeallMap.get(i)
												.get("machine_no").toString());
								Integer machine_no2 = Integer.valueOf(shapeMaps
										.get(j).get("machine_no").toString());
								if (machine_no1 == machine_no2) {
									shapeallMap.remove(i);
									i--;
									break;
								}
							}
						}
					}
					// 大于0证明预排中 还有其他机台未排
					if (shapeallMap.size() > 0) {
						for (Map<String, Object> map2 : shapeallMap) {
							// 保存与此机台同机型的数据
							if (Integer.valueOf(map2.get("machine_type")
									.toString()) == type2) {
								Map<String, Object> map3 = new HashMap<String, Object>();
								map3.put("machine_no", map2.get("machine_no"));
								map3.put("total", 0);
								shapeMaps.add(map3);
							}
						}
					}
					Integer maxtotal = 0;
					maxtotal = Integer.valueOf(shapeMaps.get(0).get("total")
							.toString());
					String machine_no = "";
					for (int j = 0; j < shapeMaps.size(); j++) {
						// 证明此型号机台还有未排上的
						Integer nowtotal = Integer.valueOf(shapeMaps.get(j)
								.get("total").toString());
						if (maxtotal != nowtotal) {
							flag = false;
							machine_no = shapeMaps.get(j).get("machine_no")
									.toString();
							break;
						}
					}
					orderperFormMap.put("now_mold_encode",
							processFormMap.get("Mold_Number"));
					orderperFormMap.put("order_number", map.get("number"));
					String suite = processFormMap.getStr("Suite");
					suite = suite.substring(0, suite.indexOf("*"));
					orderperFormMap.put("suite", suite);
					int mold_number = Integer.valueOf(map.get("number")
							.toString()) / Integer.valueOf(suite);
					orderperFormMap.put("mold_number", mold_number);
					orderperFormMap.put("remake", map.get("remake"));
					orderperFormMap.put("state", 2);
					orderperFormMap.put("order_id", map.get("id"));
					orderperFormMap.put("create_time",
							DateUtils.getStringDateTime());
					if (flag) {
						orderperFormMap.put("machine_no",
								shape.get("machine_no"));
					} else {
						orderperFormMap.put("machine_no", machine_no);
					}
					if (orderpreFormMaps.size() == 0) {

						if (shape.get("Machine_time") != null) {
							// 获取成型完成后至装机时的预留时间
							int recordTime = PublicUtils.Preloading_time
									+ PublicUtils.Stripping_time;
							orderperFormMap.put("up_moldTime", DateUtils
									.getDateadd(
											DateUtils.stringToDateTime(shape
													.get("Machine_time")
													.toString()), recordTime));
						} else {
							int recordTime = PublicUtils.Preloading_time
									+ PublicUtils.Stripping_time;
							orderperFormMap.put("up_moldTime", DateUtils
									.getDateadd(DateUtils.getDateTime(),
											recordTime));
						}
					} else {
						// 证明预排中已经有了数据
						for (Map<String, Object> orderpreFormMap : orderpreFormMaps) {
							// 如果订单的机台号中的机台号在预排中已经存在
							if (Integer.valueOf(orderpreFormMap.get(
									"machine_no").toString()) == Integer
									.valueOf(shape.get("machine_no").toString())) {
								int recordTime = PublicUtils.Preloading_time
										+ PublicUtils.Stripping_time;
								orderperFormMap
										.put("up_moldTime",
												DateUtils.getDateadd(
														DateUtils
																.stringToDateTime(orderpreFormMap
																		.get("maxtime")
																		.toString()),
														recordTime));
								// 如果不为空
								for (Map<String, Object> orderpre : orderpreFormMaps) {
									if (Integer.valueOf(orderpre.get(
											"machine_no").toString()) == Integer
											.valueOf(orderperFormMap.get(
													"machine_no").toString())) {
										String maxTime = orderpre
												.get("maxtime").toString();
										// 获取最大机台
										OrderperFormMap oFormMap = getFormMap(OrderperFormMap.class);
										oFormMap.put(
												"where",
												"where finish_time='"
														+ maxTime
														+ "' and machine_no="
														+ orderperFormMap
																.get("machine_no"));
										List<OrderperFormMap> sa = orderpreMapper
												.findByWhere(oFormMap);
										oFormMap = sa.get(0);
										oFormMap.put("wite_mold_encode",
												processFormMap
														.get("Mold_Number"));
										orderMapper.editEntity(oFormMap);
									}
								}
							}
						}
						if (orderperFormMap.get("up_moldTime") == null) {
							int recordTime = PublicUtils.Preloading_time
									+ PublicUtils.Stripping_time;
							orderperFormMap.put("up_moldTime", DateUtils
									.getDateadd(DateUtils.getDateTime(),
											recordTime));
						}

					}
					orderperFormMap.put("finish_time", DateUtils.getDateadd(
							DateUtils.stringToDateTime(orderperFormMap.get(
									"up_moldTime").toString()),
							Integer.valueOf(map.get("mintue").toString())));
					orderpreMapper.addEntity(orderperFormMap);
					OrderFormMap orderFormMap=orderMapper.findbyFrist("id", orderperFormMap.get("order_id").toString(), OrderFormMap.class);
					orderFormMap.put("production_date", DateUtils.getStringDate());
					orderMapper.editEntity(orderFormMap);
					break;
				}
			}
		}
	}
}
